import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home'
import WelCome from '../components/WelCome'
import User from '../components/user/User'
import Right from '../components/power/Rights'
import Roles from '../components/power/Roles'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/', redirect: '/login' },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: WelCome },
      { path: '/users', component: User },
      { path: '/rights', component: Right },
      { path: '/roles', component: Roles }
    ]
  }
]

const router = new VueRouter({
  routes
})

//添加一个路由守卫
//to.path 拦截的地址
//from 从哪个路径来的
//next() 通过 next('path')返回到一个地址
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    const token = window.sessionStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
